package com.quyunshuo.module.home.activity.main

import android.Manifest
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.RemoteViews
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.quyunshuo.edwincoffeetwo.common.ui.BaseActivity
import com.quyunshuo.module.home.NotificationUtils
import com.quyunshuo.module.home.R
import com.quyunshuo.module.home.databinding.HomeActivityMainBinding
import com.quyunshuo.module.home.dialog.TestDialog
import com.quyunshuo.module.home.util.AppExit
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@AndroidEntryPoint
class MainActivity : BaseActivity<HomeActivityMainBinding, HomeViewModel>() {

    companion object {
        private const val CHANNEL_ID = "asdfasdf"
        private const val NOTIFICATION_ID = 0x001

        fun newInstance(context: Context) {
            context.startActivity(Intent(context, MainActivity::class.java))
        }
    }

    // 1. 使用新权限请求API
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        notificationPermissionGranted = isGranted
        if (!isGranted) {
            Log.w("wenlong", "通知权限被拒绝")
        }
    }

    private var notificationPermissionGranted = false


    @SuppressLint("RemoteViewLayout")
    private fun getCustomNotification(context: Context): Notification? {
        try {
            val intent = Intent(context, MainActivity::class.java).apply {
                putExtra("is_activated", false)
                putExtra("entranceKey", "EntranceNotification")
                // 3. 添加任务标志
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            }

            val flags = when {
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
                else -> PendingIntent.FLAG_UPDATE_CURRENT
            }

            val pendingIntent = PendingIntent.getActivity(
                context,
                NOTIFICATION_ID,
                intent,
                flags
            )

            val collapsedView = RemoteViews(context.packageName, R.layout.home_layout_notification_collapsed)
            // 4. 使用不同的展开布局(如果可用)
            val expandedView = try {
                RemoteViews(context.packageName, R.layout.home_layout_notification_collapsed)
            } catch (e: Exception) {
                // 5. 如果展开布局不可用，仍使用折叠布局
                RemoteViews(context.packageName, R.layout.home_layout_notification_collapsed)
            }

            // 6. 设置点击事件 - 使用通知ID
            collapsedView.setOnClickPendingIntent(R.id.deactivate, pendingIntent)
            expandedView.setOnClickPendingIntent(R.id.deactivate, pendingIntent)

            return NotificationCompat.Builder(context, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_notification)
                .setStyle(NotificationCompat.DecoratedCustomViewStyle())
                .setAutoCancel(true)
                .setCustomContentView(collapsedView)
                .setCustomBigContentView(expandedView)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setContentIntent(pendingIntent)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) // 7. 在锁屏上显示
                .build()
        } catch (e: Exception) {
            // 8. 添加日志以便调试
            Log.e("wenlong", "创建通知失败", e)
            return null
        }
    }

    // 9. 显示通知方法改进
    fun showCustomNotification() {
        // 10. 检查权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (!notificationPermissionGranted) {
                Log.d("wenlong", "没有通知权限，跳过显示")
                return
            }
        }

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val notification = getCustomNotification(this)

        notification?.let {
            try {
                notificationManager.notify(NOTIFICATION_ID, it)
                Log.d("wenlong", "通知已成功发送")
            } catch (e: SecurityException) {
                // 11. 处理权限异常
                Log.e("wenlong", "显示通知权限被拒绝", e)
            }
        }
    }

    // 12. 创建通知渠道方法优化
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return

        val notificationManager = getSystemService(NotificationManager::class.java)

        // 13. 如果渠道已存在则不重复创建
        if (notificationManager.getNotificationChannel(CHANNEL_ID) != null) return

        val channelName = "重要通知"
        val importance = NotificationManager.IMPORTANCE_HIGH

        val channel = NotificationChannel(CHANNEL_ID, channelName, importance).apply {
            description = "关键功能通知"
            setShowBadge(true)
            lockscreenVisibility = Notification.VISIBILITY_PUBLIC
        }

        notificationManager.createNotificationChannel(channel)
    }

    // 14. 检查通知权限状态
    private fun checkNotificationPermission() {
        notificationPermissionGranted = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            val status = ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.POST_NOTIFICATIONS
            )
            status == PackageManager.PERMISSION_GRANTED
        } else {
            true
        }

        Log.d("wenlong", "通知权限状态: $notificationPermissionGranted")
    }

    // 15. 请求通知权限
    private fun requestNotificationPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return

        if (ActivityCompat.shouldShowRequestPermissionRationale(
                this,
                Manifest.permission.POST_NOTIFICATIONS
            )
        ) {
            // 16. 可以在这里显示解释为什么需要权限
            Log.i("wenlong", "需要向用户解释权限")
        }

        requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
    }

    private val coffeeAdapter by lazy {
        CoffeeAdapter(this@MainActivity, mViewModel.getAllList()).apply {
            setListener {
                Log.d("wenlong", "position: $it ")
                val coffeeProduct = mViewModel.getCoffeeListIndex(position = it)
                mViewModel.addCoffeeCar(coffeeProduct)
            }
        }
    }

    override val mViewModel by viewModels<HomeViewModel>()

    override fun createVB() = HomeActivityMainBinding.inflate(layoutInflater)

    // 调试方法：检查通知渠道状态
    private fun debugNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val manager = getSystemService(NotificationManager::class.java)
            val channel = manager.getNotificationChannel(CHANNEL_ID)

            channel?.let {
                Log.d("wenlong", "渠道存在: ${it.id}")
                Log.d("wenlong", "重要级: ${it.importance}")
                Log.d("wenlong", "锁屏可见: ${it.lockscreenVisibility}")
                Log.d("wenlong", "绕过勿扰: ${it.canBypassDnd()}")
            } ?: Log.e("wenlong", "渠道未创建")
        }
    }
    override fun HomeActivityMainBinding.initView() {

        // 2. 创建通知渠道
        createNotificationChannel()
        recyclerView.apply {
            layoutManager = GridLayoutManager(this@MainActivity,2)
            adapter = coffeeAdapter
        }
        // 17. 初始权限检查
        // 测试直接显示通知（无按钮）
//        showSampleNotification()
        checkNotificationPermission()
    }
    private fun showSampleNotification() {
        NotificationUtils.showNotification(
            context = this,
            title = "欢迎使用",
            content = "成功收到第一条系统通知！",
            smallIcon = R.drawable.ic_notification // 使用自己的图标
        )
    }
    override fun HomeActivityMainBinding.initListener() {
        cad.setOnClickListener {
            TestDialog.newInstance().apply {
                setCallback {
                    //删除数据
                }
                showAllowingStateLoss(supportFragmentManager,null)
            }
        }
    }

    override fun initObserve() {
        lifecycleScope.launch {
            mViewModel.coffeeCarList.collect{
                mBinding.count.text = it.size.toString()

                // 18. 只有购物车有商品时才显示通知
                if (it.isNotEmpty()) {
                    // 19. 添加延迟避免过早发送
                    delay(300)
                    showCustomNotification()
                }
            }
        }

        lifecycleScope.launch {
            mViewModel.totalPrice.collect{
                mBinding.price.text = it.toString()
            }
        }
    }

    override fun initRequestData() {
    }

    override fun onResume() {
        super.onResume()
        // 20. 在用户返回时请求权限，而不是在initView中
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !notificationPermissionGranted) {
            requestNotificationPermission()
        }
    }

    // ... 其他方法保持不变 ...
}